package com.chinasoft.maysham.manager.repo.user;

import com.chinasoft.maysham.manager.model.User;
import com.chinasoft.maysham.manager.repo.BaseRepo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

@Repository
public class UserRepo extends BaseRepo {
    public List<User> list(PageRequest pageRequest, String keyword) {
        Criteria criteria = Criteria.where("deleted").is(false);
        if (!StringUtils.isEmpty(keyword)) {
            criteria.orOperator(Criteria.where("username").regex(keyword), Criteria.where("nickName").regex(keyword));
        }
        return template.find(Query.query(criteria).with(pageRequest).with(Sort.by(Sort.Direction.ASC, "nickName")), User.class);
    }

    public List<User> findByIds(List<String> userIds, String keyword, Pageable pageable) {
        Criteria criteria = Criteria.where("id").in(userIds);
        if (!StringUtils.isEmpty(keyword)) {
            criteria.orOperator(Criteria.where("username").regex(keyword), Criteria.where("nickName").regex(keyword));
        }
        Query query = Query.query(criteria);
        if (pageable != null && pageable.isPaged()) {
            query.with(pageable).with(Sort.by(Sort.Direction.ASC, "nickName"));
        }
        return template.find(query, User.class);
    }

    public User findByUsername(String username) {
        return template.findOne(Query.query(Criteria.where("username").is(username).and("deleted").is(false)),User.class);
    }

}
